var Cate = require('../models/cate.model');
var result = [];
exports.create = function (req, res, next) {
    var cate = new Cate(req.body);
    // if(cate.parentId===""){
    //     delete cate.parentId;
    // }
    // console.log(cate);
    cate.save().then(data => {
        res.json(data);
    });
}
exports.update = function (req, res, next) {
    var id = req.params.id;
    // console.log(req.body);
    if(req.body.parentId===''){
        req.body.parentId=null;
    }
    Cate.findByIdAndUpdate(id, {
        $set: req.body
    }, {
        new: false
    }).then(data => {
        res.json(data);
    });
}
exports.get = function (req, res, next) {
    var id = req.params.id;
    Cate.findById(id).then(data => {
        res.json(data);
    });
}
exports.list = function (req, res, next) {
    var type = req.params.type;
    Cate.find({
        type: type
    }).then(data => {
        var result = getTree(data, null);
        res.json(result);
    });
}
exports.removes = function (req, res, next) {
    var id = req.body.id;
    Cate.findByIdAndDelete(id).then(data => {
        res.json({
            status: 200
        });
    });
    getTreeD(id,res);
}

function getTree(data, pid) {
    var result = [];
    var temp;
    var data = JSON.parse(JSON.stringify(data));
    for (var i in data) {
        if (data[i].parentId === pid) {
            result.push(data[i]);
            temp = getTree(data, data[i]._id);
            if (temp.length > 0) {
                data[i].children = temp;
            }
        }
    }
    return result;
}

function getTreeD(id,res) {
    Cate.find({
        parentId: id
    }).then(data => {
        if (data.length > 0) {
            for (var i in data) {
                Cate.findByIdAndDelete(data[i]._id).then(data => {
                    return res.end({
                        status: 200
                    });
                });
                getTreeD(data[i]._id,res);
            }
        }
    });
}